﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Text;
using System.Windows;
using System.Xml.Linq;
using ClientBankWPF.Entities;
using ClientBankWPF.Service;
using DevExpress.Xpf.Core;
using CryptoModule;

namespace ClientBankWPF
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {
        private readonly DataAccessService dataAccessService;
        private readonly Generators generators;
        private readonly Log log;
        private ObservableCollection<LocalUser> localUsers;
        private ObservableCollection<Client> clients;
        private ObservableCollection<Bank> banks;
        private ObservableCollection<PaymentOrder> paymentOrders;
        private readonly LocalUser currentUser;
        private int paymentOrdersCount;

        #region WindowMethods

        public MainWindow()
        {
            try
            {
                log = new Log();
                InitializeComponent();
            }
            catch (Exception exception)
            {
                log.WriteToLog(exception);
            }
        }

        public MainWindow(LocalUser currentUser)
        {
            try
            {
                log = new Log();
                InitializeComponent();
                this.currentUser = currentUser;
                Title = "Банковский модуль. ";
                switch (currentUser.Role.RoleName)
                {
                    case "администратор":
                        Title += "Администратор " + currentUser.UserName;
                        dxTabControlMainWindow.SelectedIndex = 1;
                        dxTabItemClients.Visibility = Visibility.Visible;
                        dxTabItemLocalUsers.Visibility = Visibility.Visible;
                        dxTabItemPayProviding.Visibility = Visibility.Collapsed;
                        BarButtonItemPaymentOrderPrint.IsVisible = false;
                        //BarButtonItemPaymentOrdersView.IsVisible = false;
                        //BarButtonItemReportView.IsVisible = false;
                        Height = 650;
                        Directory.CreateDirectory("ClientFilesStorage/");
                        break;
                    case "операционист":
                        Title += "Операционист " + currentUser.UserName;
                        dxTabControlMainWindow.SelectedIndex = 0;
                        dxTabItemClients.Visibility = Visibility.Collapsed;
                        dxTabItemLocalUsers.Visibility = Visibility.Collapsed;
                        dxTabItemPayProviding.Visibility = Visibility.Visible;
                        BarButtonItemPaymentOrderPrint.IsVisible = true;
                        //BarButtonItemPaymentOrdersView.IsVisible = true;
                        //BarButtonItemReportView.IsVisible = true;
                        Height = SystemParameters.PrimaryScreenHeight;
                        break;
                }
                dataAccessService = new DataAccessService();
                generators = new Generators(dataAccessService);
            }
            catch (Exception exception)
            {
                log.WriteToLog(exception);
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            switch (currentUser.Role.RoleName)
            {
                case "администратор":
                    localUsers = new ObservableCollection<LocalUser>(dataAccessService.GetLocalUsers());
                    clients = new ObservableCollection<Client>(dataAccessService.GetClients());
                    banks = new ObservableCollection<Bank>(dataAccessService.GetBanks());
                    GridControlLocalUsers.DataContext = localUsers;
                    GridControlClients.DataContext = clients;
                    GridControlBanks.DataContext = banks;
                    comboBoxRole.ItemsSource = dataAccessService.GetRoles();
                    comboBoxRole.DisplayMember = "RoleName";
                    comboBoxRole.SelectedIndex = 0;
                    break;
                case "операционист":
                    GetPaymentOrders();
                    break;
            }
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            log.Close();
            switch (currentUser.Role.RoleName)
            {
                case "администратор":
                    break;
                case "операционист":
                    foreach (var paymentOrder in paymentOrders)
                    {
                        dataAccessService.ResetPaymentOrder(paymentOrder.Id);
                    }
                    break;
            }
        }

        private void GetPaymentOrders()
        {
            paymentOrders = new ObservableCollection<PaymentOrder>(
                        dataAccessService.GetPaymentOrders(currentUser.Id));
            GridControlPaymentOrders.DataContext = paymentOrders;
            paymentOrdersCount = paymentOrders.Count;
        }

        #endregion

        #region Bar Methods

        private void BarButtonItemChangeUser_ItemClick(object sender, DevExpress.Xpf.Bars.ItemClickEventArgs e)
        {
            log.Close();
            (new LogInWindow()).Show();
            Close();
        }

        private void BarButtonItemExit_ItemClick(object sender, DevExpress.Xpf.Bars.ItemClickEventArgs e)
        {
            Close();
        }

        private void BarButtonItemPaymentOrderPrint_ItemClick(object sender, DevExpress.Xpf.Bars.ItemClickEventArgs e)
        {
            var pw = new PrintingWindow
                         {
                             DataContext = GridControlPaymentOrders.View.FocusedRow
                         };
            pw.ShowDialog();
        }

        private void BarButtonItemPaymentOrdersView_ItemClick(object sender, DevExpress.Xpf.Bars.ItemClickEventArgs e)
        {
            var paymentOrdersView = new PaymentOrdersView(dataAccessService);
            paymentOrdersView.ShowDialog();
        }

        private void BarButtonItemReportView_ItemClick(object sender, DevExpress.Xpf.Bars.ItemClickEventArgs e)
        {

        }

        #endregion

        #region LocalUsers Methods

        private void ButtonCreateLocalUserClick(object sender, RoutedEventArgs e)
        {
            var localUserAddWindow = new LocalUserAddWindow(dataAccessService);
            localUserAddWindow.ShowDialog();
            if (localUserAddWindow.LocalUser != null)
            {
                ((ObservableCollection<LocalUser>)GridControlLocalUsers.DataContext).Add(localUserAddWindow.LocalUser);
            }
        }

        private void UpdateLocalUser(LocalUser oldLocalUser)
        {
            if (checkBoxIsActive.IsChecked != null)
            {
                var newLocalUser = new LocalUser
                {
                    Id = oldLocalUser.Id,
                    Password = MD5Crypto.MD5Encode(passwordBoxLocalUserPassword.Password),
                    IdRole = ((Role)comboBoxRole.SelectedItemValue).Id,
                    UserName = textBoxUserName.Text,
                    IsActive = checkBoxIsActive.IsChecked.Value
                };
                string result = String.IsNullOrEmpty(passwordBoxLocalUserPassword.Password) ?
                    dataAccessService.UpdateLocalUser(newLocalUser) : dataAccessService.UpdateLocalUserWithPassword(newLocalUser);
                if (!String.IsNullOrEmpty(result))
                {
                    DXMessageBox.Show(result, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else
                {
                    localUsers = new ObservableCollection<LocalUser>(dataAccessService.GetLocalUsers());
                    DXMessageBox.Show("Пользователь обновлён", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
        }

        private void ButtonUpdateLocalUserClick(object sender, RoutedEventArgs e)
        {
            if (!String.IsNullOrEmpty(textBoxUserName.Text))
            {
                var oldLocalUser = (LocalUser)GridControlLocalUsers.View.FocusedRow;
                if (oldLocalUser != null)
                {
                    if (oldLocalUser.UserName != textBoxUserName.Text)
                    {
                        LocalUser localUser = dataAccessService.GetLocalUser(textBoxUserName.Text);
                        if (localUser == null)
                        {
                            UpdateLocalUser(oldLocalUser);
                        }
                        else
                        {
                            DXMessageBox.Show("Такой пользователь уже существует", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                    else
                    {
                        UpdateLocalUser(oldLocalUser);
                    }
                }
            }
            else
            {
                DXMessageBox.Show("Имя пользователя не введено", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        //private void ButtonDeleteLocalUserClick(object sender, RoutedEventArgs e)
        //{
        //    //var localUser = (LocalUser)localUsersDataGrid.SelectedItem;
        //    var localUser = (LocalUser)GridControlLocalUsers.View.FocusedRow;
        //    string result = dataAccessService.DeleteLocalUsere(localUser);
        //    if (!String.IsNullOrEmpty(result))
        //    {
        //        DXMessageBox.Show(result, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
        //    }
        //    else
        //    {
        //        localUsers.Remove(localUser);
        //        //if (localUsersDataGrid.Items.Count > 0)
        //        //{
        //        //    localUsersDataGrid.SelectedIndex = 0;
        //        //}
        //        //if (GridControlLocalUsers.Items.Count > 0)
        //        //{
        //        //    GridControlLocalUsers.SelectedIndex = 0;
        //        //}
        //        DXMessageBox.Show("Пользователь удалён", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
        //    }
        //}

        #endregion

        #region Clients Methods

        private void ButtonCreateClientClick(object sender, RoutedEventArgs e)
        {
            var clientAddWindow = new ClientAddWindow(dataAccessService);
            clientAddWindow.ShowDialog();
            if (clientAddWindow.NewClient != null)
            {
                ((ObservableCollection<Client>)GridControlClients.DataContext).Add(clientAddWindow.NewClient);
            }
        }

        private void UpdateClient(Client oldClient)
        {
            var errLst = new List<string>();
            if (textBoxClientAddress.Text.Trim().Length == 0)
            {
                errLst.Add("Поле \"Адрес\" должно быть заполнено.");
            }
            if (textBoxClientDescription.Text.Trim().Length == 0)
            {
                errLst.Add("Поле \"Описание\" должно быть заполнено.");
            }
            if (textBoxClientName.Text.Trim().Length == 0)
            {
                errLst.Add("Поле \"Имя клиента\" должно быть заполнено.");
            }
            if (textBoxClientCFO.Text.Trim().Length == 0)
            {
                errLst.Add("Поле \"Главный бухгалтер\" должно быть заполнено.");
            }
            if (errLst.Count != 0)
            {
                var msg = new StringBuilder();
                foreach (var err in errLst)
                {
                    if (msg.Length > 0) msg.Append(Environment.NewLine);
                    msg.Append(err);
                }
                DXMessageBox.Show(msg.ToString(), "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            var newClient = new Client
            {
                Address = textBoxClientAddress.Text,
                CFO = textBoxClientCFO.Text,
                Description = textBoxClientDescription.Text,
                Id = oldClient.Id,
                Name = textBoxClientName.Text,
            };
            string result = dataAccessService.UpdateClient(newClient);
            if (!String.IsNullOrEmpty(result))
            {
                DXMessageBox.Show(result, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            else
            {
                localUsers = new ObservableCollection<LocalUser>(dataAccessService.GetLocalUsers());
                DXMessageBox.Show("Клиент обновлён", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

        private void ButtonUpdateClientClick(object sender, RoutedEventArgs e)
        {
            if (!String.IsNullOrEmpty(textBoxClientName.Text))
            {
                var oldClient = (Client)GridControlClients.View.FocusedRow;
                if (oldClient.Name != textBoxClientName.Text)
                {
                    Client client = dataAccessService.GetClient(textBoxClientName.Text);
                    if (client == null)
                    {
                        UpdateClient(oldClient);
                    }
                    else
                    {
                        DXMessageBox.Show("Такой клиент уже существует", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
                else
                {
                    UpdateClient(oldClient);
                }
            }
            else
            {
                DXMessageBox.Show("Имя клиента не введено", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void ButtonDeleteClientClick(object sender, RoutedEventArgs e)
        {
            var client = (Client)GridControlClients.View.FocusedRow;
            if (client != null)
            {
                bool isDeleted;
                string result = dataAccessService.DeleteClient(client, out isDeleted);
                if (!isDeleted)
                {
                    DXMessageBox.Show(result, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else
                {
                    try
                    {
                        clients.Remove(client);
                        Directory.Delete("ClientFilesStorage/" + client.Name + "/", true);
                        DXMessageBox.Show("Клиент удалён", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
                        if (clients.Count > 0)
                        {
                            GridControlClients.View.FocusedRowHandle = 0;
                        }
                    }
                    catch (Exception)
                    {
                        DXMessageBox.Show("Клиент удалён", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
            }
        }

        #endregion

        #region Deposits Methods

        private void ButtonCreateDepositClick(object sender, RoutedEventArgs e)
        {
            var depositAddWindow = new DepositAddWindow(dataAccessService, currentUser.Id, ((Client)GridControlClients.View.FocusedRow).Id);
            depositAddWindow.ShowDialog();
            //if (clientAddWindow.NewClient != null)
            //{
            //    ((ObservableCollection<Client>)GridControlClients.DataContext).Add(clientAddWindow.NewClient);
            //}
        }

        private void ButtonUpdateDepositClick(object sender, RoutedEventArgs e)
        {
            try
            {
                decimal sum = String.IsNullOrEmpty(textBoxDepositSum.Text.Trim()) ? 0
                                  : Decimal.Parse(textBoxDepositSum.Text, NumberStyles.Any, new CultureInfo("en-US"));
                if (sum < 0)
                {
                    DXMessageBox.Show("Введена отрицательная сумма денег", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
                if (sum > Decimal.Parse("922337203685477,5807"))
                {
                    DXMessageBox.Show("Введена слишком большая сумма денег", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
                var oldDeposit = (Deposit)GridControlDeposits.View.FocusedRow;
                if (oldDeposit != null)
                {
                    var newdeposit = new Deposit
                    {
                        Id = oldDeposit.Id,
                        IdClient = oldDeposit.IdClient,
                        Number = oldDeposit.Number,
                        Sum = sum,
                        CurrencyType =
                            String.IsNullOrEmpty(textBoxDepositCurrencyType.Text.Trim())
                                ? 974
                                : Int32.Parse(textBoxDepositCurrencyType.Text)
                    };
                    string result = dataAccessService.UpdateDeposit(newdeposit);
                    if (!String.IsNullOrEmpty(result))
                    {
                        DXMessageBox.Show(result, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                    else
                    {
                        DXMessageBox.Show("Информация по счёту обновлена", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
            }
            catch (Exception exception)
            {
                DXMessageBox.Show(exception.Message, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void ButtonDeleteDepositClick(object sender, RoutedEventArgs e)
        {
            var deposit = (Deposit)GridControlDeposits.View.FocusedRow;
            if (deposit != null)
            {
                if (deposit.Sum < 0)
                {
                    DXMessageBox.Show("Счёт не может быть закрыт при отрицательном балансе", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
                if (deposit.Sum > 0)
                {
                    if (DXMessageBox.Show("На счету остались средства. При удалении счёта они будут отеряны. Продолжить?", "Информация", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes)
                    {
                        string result = dataAccessService.DeleteDeposit(deposit);
                        if (!String.IsNullOrEmpty(result))
                        {
                            DXMessageBox.Show(result, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                        else
                        {
                            DXMessageBox.Show("Счёт закрыт", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
                        }
                    }
                    else
                    {
                        return;
                    }
                }
                if (deposit.Sum == 0)
                {
                    string result = dataAccessService.DeleteDeposit(deposit);
                    if (!String.IsNullOrEmpty(result))
                    {
                        DXMessageBox.Show(result, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                    else
                    {
                        DXMessageBox.Show("Счёт закрыт", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
            }
        }

        private void ButtonAddMoneyClick(object sender, RoutedEventArgs e)
        {
            try
            {
                decimal money = String.IsNullOrEmpty(textBoxMoney.Text.Trim()) ? 0
                                  : Decimal.Parse(textBoxMoney.Text, NumberStyles.Any, new CultureInfo("ru-RU"));
                if (money < 0)
                {
                    DXMessageBox.Show("Введена отрицательная сумма денег", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
                if (money > Decimal.Parse("922337203685477,5807"))
                {
                    DXMessageBox.Show("Введена слишком большая сумма денег", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
                var oldDeposit = (Deposit)GridControlDeposits.View.FocusedRow;
                if (oldDeposit != null)
                {
                    var newDeposit = new Deposit
                    {
                        Id = oldDeposit.Id,
                        IdClient = oldDeposit.IdClient,
                        Number = oldDeposit.Number,
                        CurrencyType =
                            String.IsNullOrEmpty(textBoxDepositCurrencyType.Text.Trim())
                                ? 974
                                : Int32.Parse(textBoxDepositCurrencyType.Text)
                    };

                    var depositLog = new DepositLog
                    {
                        Id = Guid.NewGuid(),
                        IdDeposit = oldDeposit.Id,
                        IdOperationOfficer = currentUser.Id,
                        IsRefill = true,
                        Sum = money,
                        Date = DateTime.Now
                    };
                    string error = dataAccessService.AddDepositLogRecord(depositLog);
                    if (!String.IsNullOrEmpty(error))
                    {
                        DXMessageBox.Show(error, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                    newDeposit.Sum = oldDeposit.Sum + money;
                    string result = dataAccessService.UpdateDeposit(newDeposit);
                    if (!String.IsNullOrEmpty(result))
                    {
                        DXMessageBox.Show(result, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                    else
                    {
                        DXMessageBox.Show("Деньги занесены на счёт", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
                        textBoxMoney.Text = "";
                    }
                }
            }
            catch (Exception exception)
            {
                DXMessageBox.Show(exception.Message, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void ButtonSubtractMoneyClick(object sender, RoutedEventArgs e)
        {
            try
            {
                decimal money = String.IsNullOrEmpty(textBoxMoney.Text.Trim()) ? 0
                                  : Decimal.Parse(textBoxMoney.Text, NumberStyles.Any, new CultureInfo("ru-RU"));
                if (money < 0)
                {
                    DXMessageBox.Show("Введена отрицательная сумма денег", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
                if (money > Decimal.Parse("922337203685477,5807"))
                {
                    DXMessageBox.Show("Введена слишком большая сумма денег", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
                var oldDeposit = (Deposit)GridControlDeposits.View.FocusedRow;
                if (oldDeposit != null)
                {
                    var newDeposit = new Deposit
                    {
                        Id = oldDeposit.Id,
                        IdClient = oldDeposit.IdClient,
                        Number = oldDeposit.Number,
                        CurrencyType =
                            String.IsNullOrEmpty(textBoxDepositCurrencyType.Text.Trim())
                                ? 974
                                : Int32.Parse(textBoxDepositCurrencyType.Text)
                    };
                    //if ((oldDeposit.Sum - money) < 0)
                    //{
                    //    DXMessageBox.Show("На счету недостаточно средств", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                    //}
                    var depositLog = new DepositLog
                    {
                        Id = Guid.NewGuid(),
                        IdDeposit = oldDeposit.Id,
                        IdOperationOfficer = currentUser.Id,
                        IsRefill = false,
                        Sum = money,
                        Date = DateTime.Now
                    };
                    string error = dataAccessService.AddDepositLogRecord(depositLog);
                    if (!String.IsNullOrEmpty(error))
                    {
                        DXMessageBox.Show(error, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                    newDeposit.Sum = oldDeposit.Sum - money;
                    string result = dataAccessService.UpdateDeposit(newDeposit);
                    if (!String.IsNullOrEmpty(result))
                    {
                        DXMessageBox.Show(result, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                    else
                    {
                        DXMessageBox.Show("Деньги сняты со счёта", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
                        textBoxMoney.Text = "";
                    }
                }
            }
            catch (Exception exception)
            {
                DXMessageBox.Show(exception.Message, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        #endregion

        #region Bank Methods

        private void ButtonCreateBankClick(object sender, RoutedEventArgs e)
        {
            var bankAddWindow = new BankAddWindow(dataAccessService);
            bankAddWindow.ShowDialog();
            if (bankAddWindow.NewBank != null)
            {
                ((ObservableCollection<Bank>)GridControlBanks.DataContext).Add(bankAddWindow.NewBank);
            }
        }

        private void UpdateBank(Bank oldBank)
        {
            var newBank = new Bank
            {
                Id = oldBank.Id,
                Name = textBoxBankName.Text,
            };
            string result = dataAccessService.UpdateBank(newBank);
            if (!String.IsNullOrEmpty(result))
            {
                DXMessageBox.Show(result, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            else
            {
                localUsers = new ObservableCollection<LocalUser>(dataAccessService.GetLocalUsers());
                DXMessageBox.Show("Информация о банке обновлена", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

        private void ButtonUpdateBankClick(object sender, RoutedEventArgs e)
        {
            if (!String.IsNullOrEmpty(textBoxBankName.Text))
            {
                var oldBank = (Bank)GridControlBanks.View.FocusedRow;
                if (oldBank != null)
                {
                    if (oldBank.Name.ToLower() != textBoxBankName.Text.ToLower())
                    {

                        Bank bank = dataAccessService.GetBank(textBoxBankName.Text);
                        if (bank == null)
                        {
                            UpdateBank(oldBank);
                        }
                        else
                        {
                            DXMessageBox.Show("Такой банк уже существует", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                    else
                    {
                        UpdateBank(oldBank);
                    }
                }
            }
            else
            {
                DXMessageBox.Show("Наименование банка не введено", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void ButtonDeleteBankClick(object sender, RoutedEventArgs e)
        {
            var bank = (Bank)GridControlBanks.View.FocusedRow;
            if (bank != null)
            {
                string result = dataAccessService.DeleteBank(bank.Id);
                if (!String.IsNullOrEmpty(result))
                {
                    DXMessageBox.Show(result, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else
                {
                    banks.Remove(bank);
                    DXMessageBox.Show("Банк удалён", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
        }

        #endregion

        #region PaymentOrders Methods

        private void ButtonAcceptPOClick(object sender, RoutedEventArgs e)
        {
            try
            {
                var paymentOrder = (PaymentOrder)GridControlPaymentOrders.View.FocusedRow;
                Deposit oldDeposit = dataAccessService.GetDeposit(paymentOrder.PayerDepositNumber);
                string result;
                if (paymentOrder.BenefBankCode == 100)
                {
                    Deposit oldBenefDeposit = dataAccessService.GetDeposit(paymentOrder.BenefDepNum);
                    var benefDepositLog = new DepositLog
                    {
                        Id = Guid.NewGuid(),
                        IdDeposit = oldBenefDeposit.Id,
                        IdOperationOfficer = currentUser.Id,
                        IsRefill = true,
                        Sum = paymentOrder.Sum,
                        Date = DateTime.Now
                    };
                    result = dataAccessService.AddDepositLogRecord(benefDepositLog);
                    if (!String.IsNullOrEmpty(result))
                    {
                        DXMessageBox.Show(result, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                        return;
                    }
                    var newBenefDeposit = new Deposit
                    {
                        Id = oldBenefDeposit.Id,
                        IdClient = oldBenefDeposit.IdClient,
                        Number = oldBenefDeposit.Number,
                        CurrencyType = oldBenefDeposit.CurrencyType,
                        Sum = oldBenefDeposit.Sum + paymentOrder.Sum,
                    };
                    result = dataAccessService.UpdateDeposit(newBenefDeposit);
                    if (!String.IsNullOrEmpty(result))
                    {
                        DXMessageBox.Show(result, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                        return;
                    }
                }
                var depositLog = new DepositLog
                {
                    Id = Guid.NewGuid(),
                    IdDeposit = oldDeposit.Id,
                    IdOperationOfficer = currentUser.Id,
                    IsRefill = false,
                    Sum = paymentOrder.Sum,
                    Date = DateTime.Now
                };
                string error = dataAccessService.AddDepositLogRecord(depositLog);
                if (!String.IsNullOrEmpty(error))
                {
                    DXMessageBox.Show(error, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
                var newDeposit = new Deposit
                                     {
                                         Id = oldDeposit.Id,
                                         IdClient = oldDeposit.IdClient,
                                         Number = oldDeposit.Number,
                                         CurrencyType = oldDeposit.CurrencyType,
                                         Sum = oldDeposit.Sum - paymentOrder.Sum,
                                     };
                result = dataAccessService.UpdateDeposit(newDeposit);
                if (!String.IsNullOrEmpty(result))
                {
                    DXMessageBox.Show(result, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
                dataAccessService.ProcessingPaymentOrder(paymentOrder.Id, true,
                                                         !String.IsNullOrEmpty(textEditComment.Text)
                                                             ? textEditComment.Text
                                                             : null);
                paymentOrders.Remove((PaymentOrder)GridControlPaymentOrders.View.FocusedRow);
                paymentOrdersCount--;
                if (paymentOrdersCount == 0)
                {
                    ButtonLoadPO.IsEnabled = true;
                }
                DXMessageBox.Show("Платёж проведён", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (Exception exception)
            {
                DXMessageBox.Show(exception.Message, "Ошибка", MessageBoxButton.OK,
                                     MessageBoxImage.Error);
            }
        }

        private void ButtonDenyPOClick(object sender, RoutedEventArgs e)
        {
            try
            {
                if (String.IsNullOrEmpty(textEditComment.Text))
                {
                    DXMessageBox.Show("Нужно указать причину отклонения платежа", "Ошибка", MessageBoxButton.OK,
                                      MessageBoxImage.Error);
                    return;
                }
                dataAccessService.ProcessingPaymentOrder(((PaymentOrder)GridControlPaymentOrders.View.FocusedRow).Id,
                    false, textEditComment.Text);
                paymentOrders.Remove((PaymentOrder)GridControlPaymentOrders.View.FocusedRow);
                paymentOrdersCount--;
                if (paymentOrdersCount == 0)
                {
                    ButtonLoadPO.IsEnabled = true;
                }
                DXMessageBox.Show("Платёж отклонён", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (Exception exception)
            {
                DXMessageBox.Show(exception.Message, "Ошибка", MessageBoxButton.OK,
                                     MessageBoxImage.Error);
            }

        }

        private void ButtonLoadPOClick(object sender, RoutedEventArgs e)
        {
            try
            {
                GetPaymentOrders();
                ButtonLoadPO.IsEnabled = false;
                if (paymentOrdersCount == 0)
                {
                    ButtonLoadPO.IsEnabled = true;
                }
            }
            catch (Exception exception)
            {
                DXMessageBox.Show(exception.Message, "Ошибка", MessageBoxButton.OK,
                                     MessageBoxImage.Error);
            }
        }

        #endregion
    }
}